package net.jueb.frameworkDemo.orm.mongodb.springDataMongodb.codeStyle;

import java.util.Collection;
import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.mongodb.WriteResult;

import net.jueb.frameworkDemo.orm.entity.Role;
import net.jueb.frameworkDemo.orm.mongodb.springDataMongodb.MyRepository;

public class DaoRoleImpl implements MyRepository<Role> {
	
	private final MongoTemplate mongoTemplate;

	public DaoRoleImpl(MongoTemplate mongoTemplate) {
		this.mongoTemplate=mongoTemplate;
	}
	
	@Override
	public List<Role> getAllObjects() {
		return mongoTemplate.findAll(Role.class);
	}

	@Override
	public void saveObject(Role tree) {
		mongoTemplate.insert(tree);
	}
	
	public void saveObjects(Collection<Role> roles) {
		mongoTemplate.insertAll(roles);
	}


	@Override
	public Role getObject(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),Role.class);
	}

	@Override
	public WriteResult updateObject(String id, String name) {
		return mongoTemplate.updateFirst(
				new Query(Criteria.where("id").is(id)),
				Update.update("name", name), Role.class);
	}

	@Override
	public void deleteObject(String id) {
		mongoTemplate.remove(new Query(Criteria.where("id").is(id)),Role.class);
	}

	@Override
	public void createCollection() {
		if (!mongoTemplate.collectionExists(Role.class)) {
			mongoTemplate.createCollection(Role.class);
		}
	}

	@Override
	public void dropCollection() {
		if (mongoTemplate.collectionExists(Role.class)) {
			mongoTemplate.dropCollection(Role.class);
		}
	}

	@Override
	public Role findObject(String id) {
		Query query=new Query(Criteria.where("id").is(Long.parseLong(id)));
		return mongoTemplate.findOne(query, Role.class);
	}
}